import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 加减法口算练习系统-v0.2
 * 新增功能：
 * 1. 算式带答案
 * 2. 加法和≤100，减法差≥0
 * 3. 每行显示5道题（制表符对齐）
 */
public class CalculationSystemV02 {
    // 常量配置
    private static final int TOTAL_QUESTIONS = 50;
    private static final int MAX_NUMBER = 99;
    private static final int QUESTIONS_PER_LINE = 5; // 每行题数

    /**
     * 内部类：封装单个算式的完整信息（操作数、运算符、答案）
     */
    private static class Exercise {
        int num1;
        int num2;
        char operator;
        int answer;

        public Exercise(int num1, int num2, char operator, int answer) {
            this.num1 = num1;
            this.num2 = num2;
            this.operator = operator;
            this.answer = answer;
        }

        // 重写toString：返回带答案的格式化字符串
        @Override
        public String toString() {
            return String.format("%d %c %d = %d", num1, operator, num2, answer);
        }
    }

    public static void main(String[] args) {
        System.out.println("加减法口算练习系统-v0.2");
        System.out.println("=".repeat(50));

        // 生成符合约束的带答案算式
        List<Exercise> exercises = generateExercises();

        // 格式化输出（每行5道）
        printExercises(exercises);
    }

    /**
     * 生成符合约束的带答案算式
     * @return 算式列表
     */
    private static List<Exercise> generateExercises() {
        List<Exercise> exercises = new ArrayList<>(TOTAL_QUESTIONS);
        Random random = new Random();

        while (exercises.size() < TOTAL_QUESTIONS) {
            int num1 = random.nextInt(MAX_NUMBER + 1);
            int num2 = random.nextInt(MAX_NUMBER + 1);
            char operator = random.nextInt(2) == 0 ? '+' : '-';
            int answer;

            // 约束验证：加法和≤100，减法差≥0
            if (operator == '+') {
                answer = num1 + num2;
                if (answer > 100) continue; // 不符合约束，重新生成
            } else { // 减法
                if (num1 < num2) continue; // 被减数 < 减数，重新生成
                answer = num1 - num2;
            }

            // 符合约束，添加到列表
            exercises.add(new Exercise(num1, num2, operator, answer));
        }
        return exercises;
    }

    /**
     * 格式化输出算式（每行指定题数，制表符对齐）
     * @param exercises 算式列表
     */
    private static void printExercises(List<Exercise> exercises) {
        for (int i = 0; i < exercises.size(); i++) {
            System.out.printf("%s\t", exercises.get(i)); // 制表符对齐
            if ((i + 1) % QUESTIONS_PER_LINE == 0) { // 每5道换行
                System.out.println();
            }
        }
        // 确保最后一行换行
        if (exercises.size() % QUESTIONS_PER_LINE != 0) {
            System.out.println();
        }
    }
}